import json

# 要求写一个转换函数,将一个文件路径数组转成对上面3SON格式对象

a = ["index.html", "config.js", "views/Home.vue", "views/Page.vue", "views/common/Base.vue"]

a = ["index.html", "config.js", "views/Home.vue", "views/Page.vue", "views/common/Base.vue", "index.html/index.vue"
    , "views/test/test1.vue", "views/test/test2.vue"]


class Node:

    def __init__(self, val):
        self.val = val
        self.leafs = []


node = Node('')
# 数组转json，世界树
h = 0  # 树的高度


# 按层级取树节点
def dfs(node, h):
    # 遍历查找叶子节点
    for i, v in enumerate(a):
        # print(v)
        # 根据树的高度取分隔的数组，比如：h深度是1，v=views/Home.vue，当前的必然是Home.vue
        b = v.split('/')
        if len(b) > h:
            # 判断树节点是否已经在树中
            flag = False
            for n in node.leafs:
                if n.val == b[h]:
                    flag = True

            # 判断该值是否是树的子节点
            if h != 0 and node.val != b[h - 1]:
                flag = True

            # True说明不是需要的节点
            if flag:
                continue
            # 添加新的节点
            t = Node(b[h])
            node.leafs.append(t)
            # 为新的节点寻找节点
            dfs(t, h + 1)


# 遍历树-尝试转json
def print_tree(t: Node):
    arr = []
    for i, v in enumerate(t.leafs):
        print(v.val)
        json = {}
        json['label'] = v.val
        if len(v.leafs) > 0:
            json['children'] = print_tree(v)
        arr.append(json)
    return arr


if __name__ == '__main__':
    dfs(node, h)
    rs = print_tree(node)
    # 使用json包将结果转成json
    print(json.dumps(rs))
